let originalCreateElement = document.createElement;
let taskSuccess = false;
// 解析 URL 参数的函数
function parseUrlParams(url) {
  var params = {};
  var urlParts = url.split("?");
  if (urlParts.length > 1) {
    var paramString = urlParts[1];
    var paramArray = paramString.split("&");
    paramArray.forEach(function (param) {
      var pair = param.split("=");
      var key = decodeURIComponent(pair[0]);
      var value = decodeURIComponent(pair[1]);
      params[key] = value;
    });
  }
  return params;
}

// 定义全局回调函数来处理 JSONP 响应
function handleJsonpResponse(response) {
  // 在这里可以对响应数据进行处理
  if (response?.data?.resultList?.[0]?.couponActivityId) {
    taskSuccess = true;
    window.postMessage({ type: "jsonp", data: JSON.stringify(response) }, "*");
  }
  // if (
  //   response.api === "mtop.user.getUserSimple" &&
  //   response.ret[0] === "FAIL_SYS_SESSION_EXPIRED::SESSION失效"
  // ) {
  //   taskSuccess = true;
  //   window.postMessage(
  //     { type: "jsonp", data: "FAIL_SYS_SESSION_EXPIRED::SESSION失效" },
  //     "*"
  //   );
  // }
}
(function (xhr) {
  var XHR = XMLHttpRequest.prototype;
  var open = XHR.open;
  var send = XHR.send;

  XHR.open = function (method, url) {
    this._method = method;
    this._url = url;
    return open.apply(this, arguments);
  };

  XHR.send = function (postData) {
    this.addEventListener("load", function () {
      if (
        this._url.includes(
          "h5api.m.taobao.com/h5/mtop.alimama.union.at.landing.entry"
        )
      ) {
        const res = JSON.parse(this.response);
        if (
          res?.data?.data?.content?.item?.data?.resultList?.[0] &&
          res?.api == "mtop.alimama.union.at.landing.entry"
        ) {
          taskSuccess = true;
          window.postMessage({ type: "xhr", data: this.response }, "*"); // 将响应发送到 content script
        }
      }
    });
    return send.apply(this, arguments);
  };
})(XMLHttpRequest);

(function () {
  function changeReqLink(script) {
    let src;
    Object.defineProperty(script, "src", {
      get: function () {
        return src;
      },
      set: function (newVal) {
        src = newVal;
        if (src.includes("callback=mtopjsonp")) {
          // 中断原始请求
          script.onload = null;
          script.onerror = null;
          if (script.parentNode) {
            script.parentNode.removeChild(script);
          }
          const urlO = parseUrlParams(src);
          const callback = urlO.callback;
          const newSrc = src.replace(
            `callback=${callback}`,
            "callback=handleJsonpResponse"
          );
          // 重新发起 JSONP 请求
          const newScript = document.createElement("script");
          newScript.src = newSrc;
          document.head.appendChild(newScript);
        } else {
          script.setAttribute("src", newVal);
        }
      },
    });
    const originalSetAttribute = script.setAttribute;
    script.setAttribute = function () {
      const args = Array.prototype.slice.call(arguments);
      originalSetAttribute.call(script, ...args);
    };
  }
  document.createElement = function (tagName) {
    const dom = originalCreateElement.call(document, tagName);
    tagName.toLowerCase() === "script" && changeReqLink(dom);
    return dom;
  };
})();

(function () {
  let origFetch = window.fetch;
  window.fetch = async function (...args) {
    const response = await origFetch(...args);
    response
      .clone()
      .then((data) => {
        window.postMessage(
          { type: "fetch", data: URL.createObjectURL(data) },
          "*"
        ); // send to content script
      })
      .catch((err) => console.error(err));
    return response;
  };
})();

setTimeout(() => {
  if (!taskSuccess) {
    taskSuccess = true;
    window.postMessage({ type: "jsonp", data: " { data: {} }" }, "*");
  }
}, 100000);
